<?php
namespace AuctionCore\FoursStore;
use AuctionCore\FoursStore\AccountManage;
/**
 * 用户登录管理
 */
use AuctionCore\Account\Back\Employee;

/**
 * 车源列表
 * @author shijiabing
 */
class DealManage extends \AuctionSpm\Controller\BaseController {
     //初始化
    public function __construct() {           
        parent::__construct();
    }
    public function get($ev_page_num, $page) {
        
    }

    public function count() {
        
    }

    /**
     * 获取车源列表
     * @param integer $page
     * @param integer $size
     * @param array $paramer
     * @return multitype:array(list,total)
     */
    public function get_list($page = 1, $size = 10, $paramer) {
        $map = array();
        $user_m = new AccountManage();
        $map1 = $user_m->getFourMap();
        
        $map = $this->getParams($paramer);
        $map['c.suggest_max_price'] = array('gt',0);
        $map['c.suggest_min_price'] = array('gt',0);
        $map['o.order_id'] = array('gt',0);
        $map = array_merge($map,$map1);

        
        $cols = "c.car_id,c.car_no,c.brand_id,c.series_id,c.model_id,c.car_status,c.reserve_price,c.suggest_min_price,c.suggest_max_price
                ,c.composite_state,c.accident_level,c.re_auction_type,c.re_auction_reason,c.plate_prefix,c.plate_suffix,c.success_price,o.order_id,o.order_no,o.status as ostatus,o.remark_reject,co.owner_id,o.bidding_start_time,c.pointer_mileage,co.status,co.checker_id,co.check_date";
        $to =  M('cars')->alias('c')
                              ->field($cols)
                              ->join( C('DB_PREFIX') . "order o ON c.car_id=o.car_id")
                              ->join(C('DB_PREFIX')."car_owner as co ON co.owner_id=c.owner_id")
                              // ->join(C('DB_PREFIX')."car_pictures as cp ON cp.car_id=o.car_id")
                              ->where($map)->order('order_id desc')
                              ->buildSql();
        $tot = M()->table($to.' a')->group('car_id')->buildSql();
        $total = M()->table($tot.' b')->count(); 
        //子查询语句
        $subQuery = M('cars')->alias('c')
                              ->field($cols)
                              ->join( C('DB_PREFIX') . "order o ON c.car_id=o.car_id")
                              ->join(C('DB_PREFIX')."car_owner as co ON co.owner_id=c.owner_id")
                              // ->join(C('DB_PREFIX')."car_pictures as cp ON cp.car_id=o.car_id")
                              ->where($map)->order('order_id desc')
                              ->buildSql();
        $list = M()->table($subQuery.' a')->limit($size)->page($page)->group('car_id')->select();    
        // echo M()->getLastSql();         
        $cm = new \AuctionCore\CarResource\CarModel();
        //1 必须过本地,2 必须过外户,3 不限制
        //数据处理
        foreach ($list as $key => $val) {
            $list[$key] = $val;
            $brand = $cm->get_model_by_id($val['brand_id'], 'brand');
            $series = $cm->get_model_by_id($val['series_id'], 'series');
            $model = $cm->get_model_by_id($val['model_id']);
            $list[$key]['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
            $list[$key]['reserve_price'] = format_money($val['reserve_price']);
            $list[$key]['suggest_min_price'] = format_money($val['suggest_min_price']);
            $list[$key]['suggest_max_price'] = format_money($val['suggest_max_price']);
            $list[$key]['car_plate_number'] = C('PLATE_PREFIX.' . $val['plate_prefix']) . $val['plate_suffix'];
            //左前图片
            $list[$key]['left_front45'] = $this->getPics($val['car_id']);
            $in_map = array(7,8,9,10,11);
            if($val['car_status'] == '8' || $val['car_status'] == '9'){
                $list[$key]['car_status_cn'] = C('CAR_STATUS.' . $val['car_status']);//交易成功或失败
            } elseif($val['ostatus'] == '5'){
                $list[$key]['car_status_cn'] = C('ORDER_STATUS.' . $val['ostatus']);//待确认
            } elseif(in_array($val['ostatus'], $in_map)){
                $list[$key]['car_status_cn'] = '交易中';
            } elseif(in_array($val['ostatus'], array(1,2))){
                $list[$key]['car_status_cn'] = '待上拍';
            } elseif($val['ostatus'] == 3 || $val['ostatus'] == 301 || $val['ostatus'] == 4){
                $list[$key]['car_status_cn'] = '拍卖中';
            }
            //卖家信息
            $list[$key]['buger_info'] = $user_m->carToFours($val['comefrom']);
        }
        //页数
        $pages = ceil($total/$size);
        $result = array(
            'list' => $list,
            'total' => $total,
            'pages' => $pages
        );
        return $result;
    }
    /**
     * 获取图片
     * @param  [type] $car_id [description]
     * @return [type]         [description]
     */
    public function getPics($car_id){
        $map['car_id'] = $car_id;
        $map['pic_key'] = array('eq','p_left_front45'); 
        $pics = M('car_pictures')->where($map)->find();
        return $pics['pic_url'];
    }

    /**
    * 获得品牌、车系、车型信息
    * @param int $id id
    * @param string $type 类型(mbrand,brand,series,model)
    * @return array
    */
    public function get_brand_by_name($name,$type='brand'){
            $condition['name'] = array('like','%'.$name.'%');
            return M('car_'.$type)->field('brand_id')->where($condition)->getField('brand_id',true);
    }   
    public function getParams($paramer){
        $map = array();
         //car：车辆状态(0待上传协议,1 待审核,2 审核失败,3 审核驳回,4 待拍卖,5 拍卖中,6 流拍,7 待重拍, 8 交易失败, 9 交易成功)
        //order：拍单状态(1审核中,2审核驳回,3投标中,301等待竞标,4竟标中,5成效待确认,6拍单流拍,7待签约,8待付首款，
        //801已付首款,9待过户,10过户中,11待付尾款,12拍单失败,13拍单成功
        switch ($paramer['status']) {
            //全部订单
            case 1:
                $where['c.car_status'] = array('in', array('9','8'));
                $where['o.status'] = array('in', array('5','7','8','9','10','11','13'));
                $where['_logic'] = 'OR';
                $map['_complex'] = $where;
                break;
            //待确认
            case '2':
                $map['o.status'] = array('eq', 5);
                break;
            //交易中
            case '3':
                $map['o.status'] = array('in', array(7,8,9,10,11));
                break;
            //交易成功
            case '4':
                $map['c.car_status'] = array('eq', 9);
                break;
            //交易失败
            case '5':
                $map['c.car_status'] = array('in', array(2,8));
                break;
            default:
                break;
        }
        //车辆名称、车牌号、卖家信息 搜索
        if(!empty($paramer['keyword1'])){
            //车辆名称查询
            $b_result = $this->get_brand_by_name($paramer['keyword1']);
            // $b_id = $b_result['brand_id'];
            $map['c.brand_id'] = array('in',$b_result);
        } elseif(!empty($paramer['keyword2'])){
            //车牌号查询
            $first_code = mb_substr($paramer['keyword2'], 0,1,'utf-8');
            $last_code = mb_substr($paramer['keyword2'], 1,6,'utf-8');
            $plate_num = array_flip(C('PLATE_PREFIX'));
            $map['c.plate_prefix'] = array('eq',$plate_num[$first_code]);
            $map['c.plate_suffix'] = array('eq',$last_code);
        } elseif(!empty($paramer['keyword3'])){
            //拍单号查询
            $map['o.order_no'] = array('eq',$paramer['keyword3']);
        }
        //车辆检测时间
        if(!empty($paramer['start_time']) || !empty($paramer['end_time'])){
            if (empty($paramer['start_time'])) {
                $map['co.check_date'] = array("elt", $paramer['end_time'].' 23:59:59');
            } elseif (empty($paramer['end_time'])) {
                $map['co.check_date'] = array("egt", $paramer['start_time'] .' 00:00:00');
            } else {
                $map['co.check_date'] = array(array("egt", $paramer['start_time'] .' 00:00:00'), array("elt", $paramer['end_time'] .' 23:59:59'));
            }
        }
        return $map;
    }
}